package com.zyzd.general.module.countdown;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.widget.Button;

import com.zyzd.general.R;
import com.zyzd.retrofit.base.BaseFragment;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lzy on 2018/5/15 0015.
 * description ${倒计时 案例}
 */
public class CountDownFragment extends BaseFragment {

    @BindView(R.id.btnGetVerCode)
    Button mBtnGetVerCode;

    /**
     * 倒计时间隔时间
     */
    private final long mCountDownInterval = 1000;

    /**
     * 结束时间
     */
    private long mFinishTime;
    /**
     * 倒计时控制器
     */
    private CountDownTimer mCountDownTimer;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_count_down;
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onResume() {
        super.onResume();
        startCountDown();
    }

    @Override
    public void onPause() {
        super.onPause();
        cancelCountDown();
    }

    private void cancelCountDown() {
        if (mCountDownTimer == null) return;
        mCountDownTimer.cancel();
    }

    private void startCountDown() {

        if (mFinishTime == 0) {
            onBeforeCountDown();
            return;
        }

        long millisUntilFinished = mFinishTime - System.currentTimeMillis();

        if (millisUntilFinished < 0) {
            onCoundownFinish();
            return;
        }


        mCountDownTimer = new CountDownTimer(millisUntilFinished, mCountDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                updateProgress(millisUntilFinished);
            }

            @Override
            public void onFinish() {
                onCoundownFinish();
            }
        }.start();
    }

    private void onBeforeCountDown() {
        mBtnGetVerCode.setText("获取验证码");
    }

    @SuppressLint("DefaultLocale")
    private void updateProgress(long millisUntilFinished) {
        mBtnGetVerCode.setText(String.format("%ds", millisUntilFinished / mCountDownInterval));
    }

    private void onCoundownFinish() {
        mBtnGetVerCode.setText("重新获取");
    }

    @OnClick(R.id.btnGetVerCode)
    public void onClick() {
        mFinishTime = System.currentTimeMillis() + 60 * 1000;
        startCountDown();
    }
}
